<template>
  <div class="current-conversation-wrapper">
    <!-- 问题详情 -->
      <div class="content">
        <div class="message-list" ref="message-list" @scroll="this.onScroll">
          <div class="more" v-if="!isCompleted">
            <el-button
              class="test"
              type="text"
              @click="
                $store.dispatch(
                  'getMessageList',
                  currentConversation.conversationID
                )
              "
              >查看更多</el-button
            >
          </div>
          <div class="no-more" v-else>没有更多了</div>
          <message-item
            v-for="message in currentMessageList"
            :key="message.ID"
            :message="message"
          />
        </div>
        <div
          v-show="isShowScrollButtomTips"
          class="newMessageTips"
          @click="scrollMessageListToButtom"
        >
          回到最新位置
        </div>
      </div>
      <div class="footer" v-if="showMessageSendBox && +checkOverItem === 1">
        <message-send-box />
      </div>
    </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import MessageSendBox from "@/components/message/message-send-box";
import MessageItem from "@/components/message/message-item";
import { Message } from "element-ui";
import studyCenter from "@/api/studyCenter";
export default {
  name: "CurrentConversation",
  components: {
    MessageSendBox,
    MessageItem
  },
  data() {
    return {
      isShowScrollButtomTips: false,
      preScrollHeight: 0,
      showConversationProfile: false,
      timeout: "",
      hasMessageAtMe: false,
      unReadMessageCount: 0,
      //显示历史信息
      showConversationHistory: false,
      url: "", //音频播放地址
      amr: null, //amr实例
      audio: null, //生成的audio标签
      isUrlSame: false, //当前播放音频，是否和当前点击的是同一个音频
      isPlaying: false, //是否正在播放
      anwserTimer: null,
      anwserTime: 0,
      questionDetail: {}, //问题详情
      currentCommunicateType: "0",
      currentStudentMessage: {}, //当前选中问题详情
      checkOverItem: "0",
      runningTimer: null, //在线时长定时器
      lineTime: "0", //在线时长
    };
  },
  props: {
    userType: {
      type: String,
      default: "0",
    },
  },
  computed: {
    ...mapState({
      currentConversation: (state) => state.conversation.currentConversation,
      currentUnreadCount: (state) =>
        state.conversation.currentConversation.unreadCount,
      currentMessageList: (state) => state.conversation.currentMessageList,
      isCompleted: (state) => state.conversation.isCompleted,
      IsShowHistory: (state) => state.conversation.IsShowHistory,
      currentMemberList: (state) => state.group.currentMemberList,
    }),
    ...mapGetters(["toAccount", "hidden"]),
    // 是否显示当前会话组件
    showCurrentConversation() {
      return !!this.currentConversation.conversationID;
    },
    name() {
      if (this.currentConversation.type === "C2C") {
        return this.currentConversation.userProfile.nick || this.toAccount;
      } else if (this.currentConversation.type === "GROUP") {
        return (
          (this.currentConversation.groupProfile.introduction ||
            this.toAccount) + this.members
        );
      } else if (this.currentConversation.conversationID === "@TIM#SYSTEM") {
        return "系统通知";
      }
      return this.toAccount;
    },
    showMessageSendBox() {
      return this.currentConversation.type !== this.TIM.TYPES.CONV_SYSTEM;
    },
    members() {
      //计算非管理员人数
      let adminArr = this.currentMemberList.filter(
        (item) => item.role === "Admin"
      );
      let memberLen = this.currentMemberList.length;
      let adminNum = adminArr.length;
      let otherNum = memberLen - adminNum;
      return otherNum ? `（${otherNum}）` : "";
    },
  },
  mounted() {
    this.$bus.$on("getQuestionDetail", (questionItem) => {
      this.currentStudentMessage = questionItem;
      clearInterval(this.runningTimer);
      this.runningTimer = null;
      // 获取在线时长
      if (
        this.currentStudentMessage.running_time ||
        +this.currentStudentMessage.running_time === 0
      ) {
        let { running_time } = this.currentStudentMessage;
        running_time = running_time * 60;
        this.lineTime = this.dealTime(running_time);
        this.runningTimer = setInterval(() => {
          running_time++;
          this.lineTime = this.dealTime(running_time);
        }, 1000);
      }
    });
    this.$bus.$on("checkOverItem", (checkOverItem) => {
      this.checkOverItem = checkOverItem;
    });
    this.$bus.$on("checkCommunicateType", (currentCommunicateType) => {
      this.currentCommunicateType = currentCommunicateType;
    });
    this.$bus.$on("image-loaded", this.onImageLoaded);
    this.$bus.$on("scroll-bottom", this.scrollMessageListToButtom);
    this.$bus.$on("current-message-at-me", (data) => {
      this.hasMessageAtMe = data;
    });
    this.$bus.$on("current-un-read-message", (count) => {
      this.unReadMessageCount = count;
    });
    // 查看问题详情
    this.$bus.$on("checkQuestionDetail", (questionItem) => {
      this.questionDetail = questionItem;
    });
    this.$bus.$on("close-audio-play", () => {
      //切换会话的时候，关闭所有语音播放
      if (this.isPlaying) {
        if (this.audio && this.audio.play()) {
          //如果当前音频正在播放，则暂停音频并且将音频释放掉
          this.audio.pause();
          this.audio.currentTime = 0.0;
          this.isPlaying = false;
          this.audio = null;
        }
        if (this.amr) {
          //如果当前音频正在播放，则停止播放。
          this.amr.stop();
        }
        this.amr = null;
        this.isUrlSame = false;
        this.url = "";
      }
    });
    this.$bus.$on("playAudio", (data) => {
      //语音播放
      let dataUrl = data.url;
      this.isUrlSame = this.url === dataUrl ? true : false; //仅仅当amr播放时使用，arm初始化之后，url不在改变，当url改变后，需要重新初始化
      if (this.isPlaying) {
        if (this.audio && this.audio.play()) {
          //如果当前音频正在播放，则暂停音频并且将音频释放掉
          this.audio.pause();
          this.audio.currentTime = 0.0;
          this.isPlaying = false;
          this.audio = null;
        }
        if (this.amr) {
          //如果当前音频正在播放，则停止播放。
          this.amr.stop();
        }
        if (this.isUrlSame) {
          //如果当前播放音频和当前点击音频相同，则只是暂停音频，不进行接下来的播放操作
          this.url = "";
          return;
        }
      }

      this.url = dataUrl;
      this.play();
    });
    if (this.currentConversation.conversationID === "@TIM#SYSTEM") {
      return false;
    }
  },
  updated() {
    this.keepMessageListOnButtom();
    // 1. 系统会话隐藏右侧资料组件
    // 2. 没有当前会话时，隐藏右侧资料组件。
    //    背景：退出群组/删除会话时，会出现一处空白区域
    if (
      this.currentConversation.conversationID === "@TIM#SYSTEM" ||
      typeof this.currentConversation.conversationID === "undefined"
    ) {
      this.showConversationProfile = false;
    }
  },
  watch: {
    currentMessageList(next) {
      //  clearInterval(this.anwserTimer)
      //   this.anwserTime=0
      //   this.anwserTimer=setInterval(() => {
      //     this.anwserTime++
      //     console.log('123')
      //     if(this.anwserTime>10) {
      //       console.log('cccc')
      //     }
      //   }, 1000)
      if (next.length === 0 || this.unReadMessageCount <= 15) return;
      var params = {
        conversationID: this.currentConversation.conversationID,
        count: 15,
      };
      if (this.unReadMessageCount > 30) {
        this.unReadMessageCount = this.unReadMessageCount - 15;
      } else {
        params.count = this.unReadMessageCount - 15;
        this.unReadMessageCount = 0;
      }
      this.$store.commit("getAsyncMessageList", params);
    },
    currentUnreadCount(next) {
      if (!this.hidden && next > 0) {
        this.tim.setMessageRead({
          conversationID: this.currentConversation.conversationID,
        });
      }
    },
    hidden(next) {
      if (!next && this.currentUnreadCount > 0) {
        this.tim.setMessageRead({
          conversationID: this.currentConversation.conversationID,
        });
      }
    },
  },
  methods: {
    dealTime(time) {
      let h =
        parseInt(+time / 3600) < 10
          ? "0" + parseInt(+time / 3600)
          : parseInt(+time / 3600);
      let m =
        parseInt((+time / 60) % 60) < 10
          ? "0" + parseInt((+time / 60) % 60)
          : parseInt((+time / 60) % 60);
      let s =
        parseInt(+time % 60) < 10
          ? "0" + parseInt(+time % 60)
          : parseInt(+time % 60);
      return `${h}:${m}:${s}`;
    },
    // 拼贴显示url
    parseResourceUrl(url) {
      if (!url || url.includes("//")) return url;
      const cdnDomain = location.href.includes("admin.zlketang.com")
        ? "https://image.zlketang.com"
        : "https://shenji.zlketang.com";
      return cdnDomain + url;
    },
    // 接通对话
    toAsk() {
      let { id, user_account } = this.questionDetail;
      let params = { object_id: id };
      studyCenter.connectionSolution(params).then((res) => {
        if (+res.errcode === 0) {
          Message({
            type: "success",
            message: "答疑已接通",
          });
          // 发送im自定义消息打开会话窗口
        }
        this.questionDetail = {};
        this.checkOverItem = 1;
        //进入对话
        this.$bus.$emit("contactStart", {
          user_account,
        });
      });
    },
    // 结束答疑
    overAnswer() {
      this.$bus.$emit("contactEnd", {
        object_id: this.currentStudentMessage.id,
        unionid: this.currentStudentMessage.user_account,
      });
    },
    //跳转到@我的那条信息
    jumpToAlterMsg() {
      document.querySelector(".alterMe").scrollIntoView();
      this.hasMessageAtMe = false;
    },
    onScroll({ target: { scrollTop } }) {
      let messageListNode = this.$refs["message-list"];
      if (!messageListNode) {
        return;
      }
      if (
        this.preScrollHeight - messageListNode.clientHeight - scrollTop <
        20
      ) {
        this.isShowScrollButtomTips = false;
      }
    },
    // 如果滚到底部就保持在底部，否则提示是否要滚到底部
    keepMessageListOnButtom() {
      let messageListNode = this.$refs["message-list"];
      if (!messageListNode) {
        return;
      }
      // 距离底部20px内强制滚到底部,否则提示有新消息
      if (
        this.preScrollHeight -
          messageListNode.clientHeight -
          messageListNode.scrollTop <
        20
      ) {
        this.$nextTick(() => {
          messageListNode.scrollTop = messageListNode.scrollHeight;
        });
        this.isShowScrollButtomTips = false;
      } else {
        this.isShowScrollButtomTips = true;
      }
      this.preScrollHeight = messageListNode.scrollHeight;
    },
    // 直接滚到底部
    scrollMessageListToButtom() {
      this.$nextTick(() => {
        let messageListNode = this.$refs["message-list"];
        if (!messageListNode) {
          return;
        }
        messageListNode.scrollTop = messageListNode.scrollHeight;
        this.preScrollHeight = messageListNode.scrollHeight;
        this.isShowScrollButtomTips = false;
      });
    },
    showMore() {
      this.showConversationProfile = !this.showConversationProfile;
    },
    onImageLoaded() {
      this.keepMessageListOnButtom();
    },
    //播放音频
    play() {
      // this.tryPlayAMR()
      // return
      // 目前移动端的语音消息采用 aac 格式，以前用 amr 格式。默认先用 audio 标签播放，若无法播放则尝试 amr 格式播放。
      this.audio = document.createElement("audio");
      this.audio.addEventListener("error", this.tryPlayAMR); // 播放出错，则尝试使用 AMR 播放
      this.audio.src = this.url;
      this.audio.addEventListener(
        "ended",
        () => {
          //监听播放结束
          this.isPlaying = false;
        },
        false
      );
      const promise = this.audio.play();
      if (promise) {
        promise
          .then(() => {
            this.isPlaying = true;
          })
          .catch(() => {});
      }
    },
    //备用播放音频方法的创建
    tryPlayAMR() {
      try {
        const isIE = /MSIE|Trident|Edge/.test(window.navigator.userAgent);
        // amr 播放组件库在 IE 不支持
        if (isIE) {
          this.$store.commit("showMessage", {
            message:
              "您的浏览器不支持该格式的语音消息播放，请尝试更换浏览器，建议使用：谷歌浏览器",
            type: "warning",
          });
          return;
        }
        // 动态插入 amr 播放组件库
        if (!window.BenzAMRRecorder) {
          const script = document.createElement("script");
          script.addEventListener("load", this.playAMR);
          script.src = "./BenzAMRRecorder.js";
          const firstScript = document.getElementsByTagName("script")[0];
          firstScript.parentNode.insertBefore(script, firstScript);
          return;
        }
        this.playAMR();
      } catch (err) {
        this.$store.commit("showMessage", {
          message:
            "您的浏览器不支持该格式的语音消息播放，请尝试更换浏览器，建议使用：谷歌浏览器",
          type: "warning",
        });
      }
    },
    //备用播放音频
    playAMR() {
      var _this = this;
      if (!this.amr && window.BenzAMRRecorder) {
        this.amr = new window.BenzAMRRecorder();
      }
      this.amr.onPlay(function () {
        //音频开始播放的时候自动执行
        _this.isPlaying = true;
      });

      this.amr.onStop(function () {
        //音频播放停止（包括播放结束）的时候自动执行
        _this.isPlaying = false;
      });

      if (this.amr.isInit() && this.isUrlSame) {
        this.amr.play();
        return;
      }
      this.amr._isInit = false;
      this.amr.initWithUrl(this.url).then(() => {
        this.amr.play();
        this.isUrlSame = false;
      });
    },
  },
};
</script>
/* 当前会话的骨架屏 */
<style lang="stylus" scoped>
.current-conversation-wrapper {
  height: 80vh;
  background-color: $background-light;
  color: $base;
  display: flex;

  .current-conversation {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 80vh;
  }

  .profile {
    height: 80vh;
    overflow-y: scroll;
    width: 320px;
    border-left: 1px solid $border-base;
    flex-shrink: 0;
  }

  .history {
    height: 80vh;
    overflow-y: scroll;
    width: 350px;
    border-left: 1px solid $border-base;
    flex-shrink: 0;
  }

  .more {
    display: flex;
    justify-content: center;
    font-size: 12px;
  }

  .no-more {
    display: flex;
    justify-content: center;
    color: $secondary;
    font-size: 12px;
    padding: 10px 10px;
  }
}

.user-type-header {
  border-bottom: 1px solid $border-base;
  position: relative;
  height: 120px;
  padding: 28px 16px;

  .contact-con {
  }

  .user-header-img {
    width: 64px;
    height: 64px;
    margin-right: 12px;
    vertical-align: -12px;
  }

  .user-con {
    display: inline-block;
  }

  .user-name {
    font-size: 20px;
    font-weight: 600;
    color: #262626;
    line-height: 28px;
    margin-right: 12px;
  }

  .user-type {
    font-size: 14px;
    font-weight: 400;
    color: #3480FF;
    line-height: 24px;
    background: #D6EBFF;
    border-radius: 2px;
    padding: 0 8px;
  }

  .user-bottom {
    margin-top: 8px;
    font-size: 16px;
    font-weight: 400;
    color: #3480FF;
    line-height: 22px;
  }
}

.header {
  border-bottom: 1px solid $border-base;
  height: 50px;
  position: relative;

  .name {
    display: inline-block;
    padding: 0 20px;
    color: $base;
    font-size: 18px;
    font-weight: bold;
    line-height: 50px;
    // text-shadow: $font-dark 0 0 0.1em;
  }

  .btn-more-info {
    position: absolute;
    top: 10px;
    right: -15px;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    cursor: pointer;

    &::before {
      position: absolute;
      right: 0;
      z-index: 0;
      content: '';
      width: 15px;
      height: 30px;
      border: 1px solid $border-base;
      border-radius: 0 100% 100% 0 / 50%;
      border-left: none;
      background-color: $background-light;
    }

    &::after {
      content: '';
      width: 8px;
      height: 8px;
      transition: transform 0.8s;
      border-top: 2px solid $secondary;
      border-right: 2px solid $secondary;
      float: right;
      position: relative;
      top: 11px;
      right: 8px;
      transform: rotate(45deg);
    }

    &.left-arrow {
      transform: rotate(180deg);

      &::before {
        background-color: $white;
      }
    }

    &:hover {
      &::after {
        border-color: $light-primary;
      }
    }
  }
}

.content {
  display: flex;
  flex: 1;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  position: relative;

  .message-list {
    width: 100%;
    box-sizing: border-box;
    overflow-y: scroll;
    padding: 0 20px;

    .message-alter-me {
      position: absolute;
      top: 50px;
      right: 20px;
      font-size: 14px;
      color: rgba(255, 145, 122, 1);
      cursor: pointer;
    }
  }

  .newMessageTips {
    position: absolute;
    cursor: pointer;
    padding: 5px;
    width: 120px;
    margin: auto;
    left: 0;
    right: 0;
    bottom: 5px;
    font-size: 12px;
    text-align: center;
    border-radius: 10px;
    border: $border-light 1px solid;
    background-color: $white;
    color: $primary;
  }
}

.footer {
  border-top: 1px solid $border-base;
}

.show-more {
  text-align: right;
  padding: 10px 20px 0 0;
}
.no-active-tip{
  position: relative;
  width :100%;
  height :100%
}
.no-active-tip-img{
  position: absolute;
  top:50%;
  left: 50%;
  transform: translate(-50%,-50%);
   width :400px;
  height :243px
}
.no-active-tip-text{
  position: absolute;
  left: 0;
  top :560px;
  padding-left: 50px;
  width :100%;
  text-align: center;
  box-sizing: border-box;
}
.question-detail-box{
  padding:0 16px;
  width :100%
}
.question-detail-head{
  position: relative;
  display: flex;
  padding:28px  0;
  width: 100%;
  border-bottom: 1px solid #D9D9D9;
}
.question-detail-head-img{
  margin-right:12px;
  width: 64px;
height: 64px;
border: 1px solid #F0F0F0;
}
.question-detail-head-name{
  padding-top:6px;
  margin-bottom:8px;
  font-size: 20px;
font-weight: 600;
color: #262626;
line-height: 28px;
}
.question-detail-head-status{
  font-size: 16px;
font-weight: 400;
color: #84BAFF;
line-height: 22px;
}
.question-detail-content{
  box-sizing: border-box;
  padding:20px 0;
  width:100%;
  height:550px;
  overflow-y: auto;
  border-bottom: 1px solid #D9D9D9;
}
.question-detail-content-item{
  display: flex;
  margin-bottom: 20px
}
.question-detail-content-head-img{
  margin-right:12px;
  width :42px;
  height:42px;
}
.question-detail-content-text{
  padding:12px;
  max-width:500px;
  background: #FFFFFF;
border-radius: 4px;
}
.question-detail-bottom{
  position:relative;
  width:100%;
  height:160px;
}
.question-detail-bottom-btn{
  position: absolute;
  top:50%;
  left:50%;
  --webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
  width :170px;
  height: 44px;
  line-height: 44px;
  text-align: center;
  font-size: 16px;
font-weight: 600;
color: #FFFFFF;
background: #3480FF;
cursor:pointer;
}
.question-detail-head-over{
    font-size: 16px;
font-weight: 400;
color: #8C8C8C;
line-height: 22px;
}
.close-dialogue{
  position: absolute;
  top:28px;
  right:16px;
}
.close-dialogue-btn{
  position: relative;
  width: 76px;
  height :42px;
  background: #FF6046;
  cursor :pointer;
}
.close-dialogue-tip{
  margin-top:2px;
  text-align: center;
  font-size: 14px;
font-weight: 600;
color: #8C8C8C;
line-height: 20px;
}
.close-dialogue-icon{
  position: absolute;
  top:50%;
  left:50%;
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
  width :23px;
  height :23px;
}
</style>
